$PySpark$ 在遇到$map$类型的列的一些处理
在$spark$中,有时会遇到$column$的类型是$array$和$map$类型的,这时候需要将它们转换为多行数据
$Explode\ array\ and\ map\ columns\ to\ rows$
1 | import pyspark |
1 | root |
$explode – array\ column\ example$
$PySpark\ function$
explode(e: Column)
is used to explode or create array or map columns to rows. When an array is passed to this function, it creates a new default column “col1” and it contains all array elements. When a map is passed, it creates two new columns one for key and one for value and each element in map split into the rows.$spark$提供$explode$函数
explode(e: Column)
, 当传入的column是array类型时,它会新建一个列,默认列名为col
;当传入的column是map类型时,则会新建两个列,一个列为key,另一个为value
1 | from pyspark.sql.functions import explode |
$output$
1 |
|
注意:
Washington
对应的$knownLanguages$字段是null,explode会忽略这种值,可以看到,结果集里并没有Washington
的记录,如果需要保留,使用explode_outer
函数
$explode – map\ column\ example$
1 | from pyspark.sql.functions import explode |
$output$
1 | root |
$How\ to\ covert\ Map\ into\ multiple\ columns$
有时候需要把$Map$类型的$colum$n进行以$key$为列名,$value$为列值的处理。如下:
1 | from pyspark.sql import functions as F |
$output$
1 | +----------+----------+---------+ |